#include "remote_tree_model.h"

RemoteTreeNode::RemoteTreeNode(const QString &_data, RemoteTreeNode *_parent)
	:data(_data), parent(_parent)
{
	if (parent)
		parent->children.push_back(this);
}

RemoteTreeNode RemoteTreeNode::add_child(const QString &_data) {
	return RemoteTreeNode(_data, this);
}

uint RemoteTreeNode::num_children () const {
	return children.length();
}

RemoteTreeNode RemoteTreeNode::child(uint i) const {
	return *children[i];
}

RemoteTreeNode::~RemoteTreeNode () {
	for (QList<RemoteTreeNode*>::iterator it = children.begin(); it != children.end(); ++it)
		delete (*it);
}

bool RemoteTreeNode::operator == (RemoteTreeNode &rtn) {
	if (data == rtn.data && children.length() == rtn.children.length()) {
		QList<RemoteTreeNode*>::iterator i = children.begin(), j = rtn.children.begin();
		for (QList<RemoteTreeNode*>::iterator it = children.begin(); it != children.end(); ++it)
			if (**i != **j)
				return false;
		return true;
	}
	return false;
}

bool RemoteTreeNode::operator != (RemoteTreeNode &rtn) {
	return !(*this == rtn);
}

QVariant RemoteTreeNode::extract_data(const QModelIndex &index) {
	return cast_model_index(index)->data;
}

RemoteTreeNode* RemoteTreeNode::cast_model_index (const QModelIndex &index) {
	RemoteTreeNode *rtn = static_cast<RemoteTreeNode*>(index.internalPointer());
	if (rtn)
		return rtn;
	else
		throw my_exception("There is a node, the type of which is not RemoteTreeNode");
}

QModelIndex RemoteTreeModel::index(int row, int column, const QModelIndex &parent) const {
	if (parent == QModelIndex())
		return *root_node;
	else
		return createIndex(row, column, (RemoteTreeNode::cast_model_index(parent))->children[0]);
}

QModelIndex RemoteTreeModel::parent(const QModelIndex &child) const {
	return *RemoteTreeNode::cast_model_index(child)->parent;
}

int RemoteTreeModel::rowCount(const QModelIndex &parent) const {
	return RemoteTreeNode::cast_model_index(parent)->children.length();
}

int RemoteTreeModel::columnCount(const QModelIndex &parent) const {
	return 1;
}

QVariant RemoteTreeModel::data(const QModelIndex &index, int role) const {
	return RemoteTreeNode::extract_data(index);
}

bool RemoteTreeModel::operator == (const RemoteTreeModel &rtm) {
	return *root_node == *rtm.root_node;
}

bool RemoteTreeModel::operator != (const RemoteTreeModel &rtm) {
	return !(*this == rtm);
}

RemoteTreeModel* RemoteTreeModel::construct_from_QFileSystemModel (const QFileSystemModel &fsm) {
	//QDir fsm.rootDirectory();

	return 0;
}
